<template>
  <div class="container">
    <h2 class="title">欢迎回来</h2>
    <InputForm
        :columns="columns"
        :handler="handler"
        :model="signInForm"
        :need-button="true"
        :rules="rules"
        :show-label="false"
        button-content="登陆"
        form-style="width: 300px"
    />
  </div>
</template>
<script setup>

import {inject, ref} from "vue";
import InputForm from "../common/InputForm.vue";
import {login} from "../../api/userApi.js";
import {useMessage} from "naive-ui";
import {useRoute, useRouter} from "vue-router";
import {setStorageObject, setStorageString} from "../../utils/localStorage.js";
import {MD5} from "../../utils/utils.js";

const secretKey = inject('secretKey')
const message = useMessage()
const router = useRouter()
const {query} = useRoute();

const signInForm = ref({
  loginKey: null,
  password: null,
})

const columns = ref([
  {
    name: "loginKey",
    style: "width: 300px",
    round: true,
    placeholder: "用户名或邮箱",
  },
  {
    name: "originPassword",
    style: "width: 300px",
    round: true,
    placeholder: "密码",
    type: "password",
    showPasswordOn: "mousedown"
  }
])

const rules = {
  loginKey: [
    {
      required: true,
      message: "嗨呀，用户名不写咋登陆呀😲",
      trigger: 'blur'
    }
  ],
  password: [
    {
      validator: validatePassword,
      trigger: ['blur', 'input']
    }
  ]
}

function validatePassword(rule, value) {
  if (!value) {
    return new Error("喂喂喂还没输密码呢😫")
  }
  if (!/^(?=.*\d)(?=.*[a-zA-Z])(?=.*[^\da-zA-Z\s]).{8,20}$/.test(value)) {
    return new Error("必须包含大小写字母和数字的组合，不能使用特殊字符，长度在 8-20 之间😫")
  }
  return true;
}

function handler() {
  signInForm.value.password = MD5(secretKey.value, signInForm.value.originPassword)
  delete signInForm.value.originPassword
  login(signInForm.value).then(resp => {
    setStorageString('token', resp.data.token)
    setStorageObject('userInfo', {
      uid: resp.data.id,
      email: resp.data.email,
      nickName: resp.data.nickName,
      userName: resp.data.userName
    })
    message.success("登陆成功")
    router.push(query.target ? query.target : '/')
  }).catch(err => {
    console.log(err)
  })
}
</script>
<style scoped>
@import '../../css/login.css';

</style>